<!--
 * @copyright 2025 银杏ERP
 * @author 银杏ERP
 * @version 1.0
 * @license http://www.hhyx.xyz
 * @developer Lhf
-->

<template>
    <el-card shadow="hover" class="product-turnover-card">
        <template #header>
            <div class="card-header">
                <div class="title-with-icon">
                    <Icon name="fa fa-refresh" class="title-icon" />
                    <span>{{ t('产品周转率') }}</span>
                </div>
                <div class="header-actions">
                    <el-select v-model="timeRange" size="small" @change="handleTimeRangeChange">
                        <el-option label="本周" value="week" />
                        <el-option label="本月" value="month" />
                        <el-option label="本季度" value="quarter" />
                    </el-select>
                </div>
            </div>
        </template>
        <div v-loading="loading" class="turnover-content">
            <div class="turnover-chart">
                <div ref="chartRef" class="chart-container"></div>
            </div>
            <div class="turnover-analysis">
                <div class="analysis-header">
                    <div class="analysis-title">{{ t('周转排名') }}</div>
                    <div class="analysis-tabs">
                        <el-radio-group v-model="rankingType" size="small" @change="handleRankingChange">
                            <el-radio-button label="high">{{ t('最高') }}</el-radio-button>
                            <el-radio-button label="low">{{ t('最低') }}</el-radio-button>
                        </el-radio-group>
                    </div>
                </div>
                <div class="ranking-list">
                    <div v-for="(item, index) in rankingList" :key="index" class="ranking-item">
                        <div class="ranking-number" :class="getRankingClass(index)">{{ index + 1 }}</div>
                        <div class="product-info">
                            <div class="product-name" :title="item.name">{{ item.name }}</div>
                            <div class="product-category">{{ item.category }}</div>
                        </div>
                        <div class="turnover-rate">
                            <div class="rate-value" :class="getRateClass(item.rate, rankingType)">
                                {{ item.rate }}
                            </div>
                            <div class="trend-indicator">
                                <Icon
                                    :name="item.trend > 0 ? 'fa fa-long-arrow-up' : 'fa fa-long-arrow-down'"
                                    :class="item.trend > 0 ? 'trend-up' : 'trend-down'"
                                />
                                <span>{{ Math.abs(item.trend) }}%</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="analysis-footer">
                    <el-alert
                        :title="analysisMessage"
                        type="info"
                        :closable="false"
                        show-icon
                    />
                </div>
            </div>
        </div>
    </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import Icon from '/@/components/icon/index.vue'

// 注册 ECharts 必须的组件
echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    BarChart,
    CanvasRenderer
])

const { t } = useI18n()

const chartRef = ref<HTMLElement | null>(null)
const loading = ref(false)
let chart: echarts.ECharts | null = null
const timeRange = ref('month')
const rankingType = ref('high')

// 周转率数据
const weekData = [
    { category: '电子设备', rate: 2.1 },
    { category: '办公用品', rate: 1.8 },
    { category: '食品饮料', rate: 3.5 },
    { category: '医疗耗材', rate: 1.2 },
    { category: '家具器材', rate: 0.6 }
]

const monthData = [
    { category: '电子设备', rate: 3.2 },
    { category: '办公用品', rate: 2.7 },
    { category: '食品饮料', rate: 5.8 },
    { category: '医疗耗材', rate: 1.9 },
    { category: '家具器材', rate: 1.1 }
]

const quarterData = [
    { category: '电子设备', rate: 4.5 },
    { category: '办公用品', rate: 3.9 },
    { category: '食品饮料', rate: 8.7 },
    { category: '医疗耗材', rate: 2.8 },
    { category: '家具器材', rate: 1.6 }
]

// 高周转率排名数据
const highTurnoverData = [
    { id: 1, name: '矿泉水550ml', category: '食品饮料', rate: '9.2次/月', trend: 15 },
    { id: 2, name: '一次性口罩', category: '医疗耗材', rate: '7.8次/月', trend: 22 },
    { id: 3, name: 'A4打印纸', category: '办公用品', rate: '6.5次/月', trend: -5 },
    { id: 4, name: '咖啡胶囊', category: '食品饮料', rate: '5.9次/月', trend: 8 },
    { id: 5, name: 'USB数据线', category: '电子设备', rate: '5.2次/月', trend: 3 }
]

// 低周转率排名数据
const lowTurnoverData = [
    { id: 6, name: '会议桌', category: '家具器材', rate: '0.3次/月', trend: -12 },
    { id: 7, name: '档案柜', category: '家具器材', rate: '0.4次/月', trend: -8 },
    { id: 8, name: '投影仪', category: '电子设备', rate: '0.5次/月', trend: -2 },
    { id: 9, name: '空气净化器', category: '电子设备', rate: '0.7次/月', trend: 5 },
    { id: 10, name: '传真机', category: '办公用品', rate: '0.8次/月', trend: -18 }
]

const rankingList = ref(highTurnoverData)

// 分析消息
const analysisMessage = computed(() => {
    if (rankingType.value === 'high') {
        return t('食品饮料类商品周转率最高，建议适当增加库存以满足需求')
    } else {
        return t('家具器材类商品周转率较低，建议减少库存或考虑促销')
    }
})

// 获取排名样式
const getRankingClass = (index: number): string => {
    const classList = ['rank-first', 'rank-second', 'rank-third']
    return index < 3 ? classList[index] : ''
}

// 获取周转率样式
const getRateClass = (rate: string, rankingType: string): string => {
    const numericRate = parseFloat(rate.split('次')[0])
    if (rankingType === 'high') {
        return numericRate > 7 ? 'rate-excellent' : numericRate > 5 ? 'rate-good' : 'rate-normal'
    } else {
        return numericRate < 0.5 ? 'rate-poor' : numericRate < 0.8 ? 'rate-warning' : 'rate-normal'
    }
}

// 切换时间范围
const handleTimeRangeChange = () => {
    initChart()
}

// 切换排名类型
const handleRankingChange = () => {
    loading.value = true
    
    // 模拟加载过程
    setTimeout(() => {
        rankingList.value = rankingType.value === 'high' ? highTurnoverData : lowTurnoverData
        loading.value = false
    }, 300)
}

// 初始化图表
const initChart = () => {
    if (!chartRef.value) return
    
    loading.value = true
    
    // 销毁之前的图表实例
    if (chart) {
        chart.dispose()
    }
    
    chart = echarts.init(chartRef.value)
    
    // 获取当前时间范围的数据
    let data
    if (timeRange.value === 'week') {
        data = weekData
    } else if (timeRange.value === 'month') {
        data = monthData
    } else {
        data = quarterData
    }
    
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: (params: any) => {
                const dataIndex = params[0].dataIndex
                return `${data[dataIndex].category}<br/>周转率: ${data[dataIndex].rate}次/${timeRange.value === 'week' ? '周' : timeRange.value === 'month' ? '月' : '季度'}`
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: data.map(item => item.category),
            axisLabel: {
                interval: 0,
                rotate: 30,
                color: '#606266'
            },
            axisLine: {
                lineStyle: {
                    color: '#dcdfe6'
                }
            }
        },
        yAxis: {
            type: 'value',
            name: `周转率(次/${timeRange.value === 'week' ? '周' : timeRange.value === 'month' ? '月' : '季度'})`,
            nameTextStyle: {
                color: '#909399',
                padding: [0, 0, 0, 20]
            },
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#606266'
            },
            splitLine: {
                lineStyle: {
                    color: '#ebeef5',
                    type: 'dashed'
                }
            }
        },
        series: [
            {
                type: 'bar',
                data: data.map(item => ({
                    value: item.rate,
                    itemStyle: {
                        // 不同类别使用不同颜色
                        color: item.category === '电子设备' ? '#42A5F5' :
                              item.category === '办公用品' ? '#66BB6A' :
                              item.category === '食品饮料' ? '#FFA726' :
                              item.category === '医疗耗材' ? '#EC407A' :
                              '#78909C'
                    }
                })),
                barWidth: '50%',
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}',
                    color: '#606266'
                }
            }
        ]
    }
    
    chart.setOption(option)
    loading.value = false
}

// 窗口调整时重绘图表
const handleResize = () => {
    chart?.resize()
}

// 监听窗口大小变化
window.addEventListener('resize', handleResize)

// 组件卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    chart?.dispose()
})

// 组件挂载完成后初始化
onMounted(() => {
    nextTick(() => {
        initChart()
    })
})
</script>

<style scoped lang="scss">
.product-turnover-card {
    height: 360px;
    margin-bottom: 20px;
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title-with-icon {
            display: flex;
            align-items: center;
            
            .title-icon {
                color: #42A5F5;
                margin-right: 8px;
                font-size: 16px;
            }
        }
        
        .header-actions {
            display: flex;
            align-items: center;
        }
    }
    
    .turnover-content {
        display: flex;
        height: 280px;
        
        .turnover-chart {
            flex: 1;
            height: 100%;
            
            .chart-container {
                width: 100%;
                height: 100%;
            }
        }
        
        .turnover-analysis {
            width: 220px;
            padding-left: 15px;
            display: flex;
            flex-direction: column;
            
            .analysis-header {
                margin-bottom: 10px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                
                .analysis-title {
                    font-weight: bold;
                    font-size: 14px;
                    color: #303133;
                }
            }
            
            .ranking-list {
                flex: 1;
                overflow-y: auto;
                
                .ranking-item {
                    display: flex;
                    padding: 6px 0;
                    align-items: center;
                    border-bottom: 1px dashed #ebeef5;
                    
                    &:last-child {
                        border-bottom: none;
                    }
                    
                    .ranking-number {
                        width: 22px;
                        height: 22px;
                        border-radius: 50%;
                        background-color: #f0f2f5;
                        color: #606266;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        font-size: 12px;
                        margin-right: 8px;
                        
                        &.rank-first {
                            background-color: #f56c6c;
                            color: white;
                        }
                        
                        &.rank-second {
                            background-color: #e6a23c;
                            color: white;
                        }
                        
                        &.rank-third {
                            background-color: #409eff;
                            color: white;
                        }
                    }
                    
                    .product-info {
                        flex: 1;
                        overflow: hidden;
                        
                        .product-name {
                            font-size: 13px;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                        }
                        
                        .product-category {
                            font-size: 12px;
                            color: #909399;
                        }
                    }
                    
                    .turnover-rate {
                        display: flex;
                        flex-direction: column;
                        align-items: flex-end;
                        
                        .rate-value {
                            font-weight: bold;
                            font-size: 14px;
                            
                            &.rate-excellent {
                                color: #67c23a;
                            }
                            
                            &.rate-good {
                                color: #409eff;
                            }
                            
                            &.rate-normal {
                                color: #606266;
                            }
                            
                            &.rate-warning {
                                color: #e6a23c;
                            }
                            
                            &.rate-poor {
                                color: #f56c6c;
                            }
                        }
                        
                        .trend-indicator {
                            font-size: 12px;
                            display: flex;
                            align-items: center;
                            gap: 3px;
                            
                            .trend-up {
                                color: #67c23a;
                            }
                            
                            .trend-down {
                                color: #f56c6c;
                            }
                        }
                    }
                }
            }
            
            .analysis-footer {
                margin-top: 10px;
            }
        }
    }
}

@media screen and (max-width: 1200px) {
    .product-turnover-card {
        height: auto;
        
        .turnover-content {
            flex-direction: column;
            height: auto;
            
            .turnover-chart {
                height: 200px;
                margin-bottom: 15px;
            }
            
            .turnover-analysis {
                width: 100%;
                padding-left: 0;
                
                .ranking-list {
                    max-height: 200px;
                }
            }
        }
    }
}
</style> 